///////////////////////////////////////////////////////////////////////////////
// File:        TcpConnectionInputStream.cc
// Author:      671643387@qq.com
// Description:
///////////////////////////////////////////////////////////////////////////////

#include "common/TcpConnection.hpp"
#include "common/TcpConnectionInputStream.hpp"
using namespace monkey::common;

#define __INN_MIN(a, b) ((a) > (b)) ? (b) : (a)

TcpConnectionInputStream::TcpConnectionInputStream(TcpConnection& conn)
    : TcpConnectionStream(conn)
{

}

TcpConnectionInputStream::~TcpConnectionInputStream()
{

}

int TcpConnectionInputStream::Fill()
{
    if (Space() == 0)
        return 0;

    char buff[TCP_CONN_STREAM_SIZE];
    unsigned int bytsReadAll = 0;

    while (Space() > 0)
    {
        int bytsRead = pio_connection_read(conn_.conn_, 
            buff, __INN_MIN(TCP_CONN_STREAM_SIZE, Space()), 0);
        if (bytsRead < 0)
        {
            if (bytsRead == SOCKET_ERROR)
                return SOCKET_ERROR;
            else if (bytsRead == SOCKET_ERROR_WOULDBLOCK)
                break;
        }
        else if (bytsRead == 0)
        {
            return SOCKET_ERROR;
        }

        Write(buff, (unsigned int)bytsRead);
        bytsReadAll += (unsigned int)bytsRead;
    }

    return bytsReadAll;
}
